import { Component, OnInit } from '@angular/core';
import { RequestService } from '../../../service/request/request.service';
import { Router } from '@angular/router';
import { SELECTPEOPLE } from '../../../service/constant';
import { LoadingController } from '@ionic/angular';

@Component({
  selector: 'app-select-peop-or-unit',
  templateUrl: './select-peop-or-unit.component.html',
  styleUrls: ['./select-peop-or-unit.component.scss'],
})
export class SelectPeopOrUnitComponent implements OnInit {
  list: any[] = [];
  originalData: any[] = [];
  constructor(private http: RequestService, private router: Router, private loading: LoadingController) {}
  ngOnInit() {
    this.getList();
  }
  Selected() {
    const selected = localStorage.getItem(SELECTPEOPLE) ? JSON.parse(localStorage.getItem(SELECTPEOPLE)) : [];
    this.list.map((item, index) => {
      const result = selected.find((value) => value.username === item.username);
      if (result) {
        item.isChecked = true;
      } else {
        item.isChecked = false;
      }
    });
    console.log(this.list, 'list');
  }
  async getList() {
    const loading = await this.loading.create({
      message: '数据加载中...',
      backdropDismiss: false,
    });
    await loading.present();
    this.http.get('sys/user/list', { pageSize: 1000 }).subscribe((res) => {
      console.log(res, 'res');
      if (res && res.code === 0) {
        this.list = res.result.records;
        this.originalData = res.result.records;
        // 处理默认选中问题
        this.Selected();
        loading.dismiss();
      }
    });
    setTimeout(() => {
      loading.dismiss();
    }, 5000);
  }
  // 搜索框变化的时候
  Change(val) {
    const data = val.detail.value;
    if (data) {
      let restr_list = [];
      this.list.map((item) => {
        if (item.username.indexOf(data) !== -1) {
          restr_list.push(item);
        }
      });
      this.list = restr_list;
    } else {
      this.list = Object.assign([], this.originalData);
    }
  }
  // 确定选择
  SelectChoice() {
    /**
     * 过滤出选择的人员
     */
    let select_people = [];
    this.list.forEach((item) => {
      if (item.isChecked) {
        select_people.push(item);
      }
    });
    if (select_people.length > 0) {
      localStorage.setItem(SELECTPEOPLE, JSON.stringify(select_people));
      this.router.navigateByUrl('/add-document');
    } else {
      this.http.showToast('请选择人员!');
    }
  }
  // 清空选择
  ClearSelect() {
    localStorage.removeItem(SELECTPEOPLE);
    this.Selected();
  }
}
